import React, { useCallback } from 'react';
import { FlatList, View, Text, StyleSheet, ActivityIndicator, StyleProp, ViewStyle } from 'react-native';
import NoMore from './NoMore.tsx';
import LoadingIndicator from './LoadingIndicator.tsx';
import Empty from './Empty.tsx';

interface CustomFlatListProps<T> {
  data: T[]; // 列表数据
  renderItem: ({ item, index }: { item: T; index: number }) => JSX.Element; // 渲染每一项的函数
  onEndReached: () => void; // 触底加载的回调函数
  onRefresh?: () => void; // 下拉刷新回调函数
  refreshing?: boolean; // 下拉刷新状态
  isLoading: boolean; // 外部传入的加载状态，用于判断是否正在加载中
  noDataText?: string; // 无数据时显示的文本，默认为 "暂无数据"
  style?: StyleProp<ViewStyle>;
  isRefresh?: boolean;
  ListHeaderComponent?:() => JSX.Element
}

const CustomFlatList = <T extends unknown>({ data, renderItem,ListHeaderComponent, onEndReached, refreshing, onRefresh, isLoading, isRefresh = true, noDataText = '暂无数据', style }: CustomFlatListProps<T>) => {
  /**
   * 触底加载事件
   */
  const handleEndReached = useCallback(() => {
    if (!isLoading) {
      onEndReached();
    }
  }, [isLoading, onEndReached]);

  /**
   * 下拉刷新
   */
  const handleRefresh = useCallback(() => {
    if (onRefresh) onRefresh();
  }, [refreshing, onRefresh]);

  return (
    <>
      {isRefresh && (
        <FlatList
          data={data}
          ListHeaderComponent={ListHeaderComponent}
          renderItem={renderItem}
          style={style}
          keyExtractor={(item, index) => index.toString()}
          ListEmptyComponent={<Empty text={noDataText || '暂无更多数据'} />}
          ListFooterComponent={data.length > 0 ? isLoading ? <LoadingIndicator text={'加载中'} /> : <NoMore /> : null}
          onEndReached={handleEndReached}
          onRefresh={handleRefresh}
          refreshing={refreshing}
          onEndReachedThreshold={0.1}
        />
      )}
      {!isRefresh && <FlatList data={data} ListHeaderComponent={ListHeaderComponent} renderItem={renderItem} style={style} keyExtractor={(item, index) => index.toString()} ListEmptyComponent={<Empty text={noDataText || '暂无更多数据'} />} ListFooterComponent={data.length > 0 ? isLoading ? <LoadingIndicator text={'加载中'} /> : <NoMore /> : null} onEndReached={handleEndReached} onEndReachedThreshold={0.2} />}
    </>
  );
};

const styles = StyleSheet.create({
  emptyContainer: {
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  loadingContainer: {
    justifyContent: 'center',
    alignItems: 'center',
    padding: 10,
  },
});

export default CustomFlatList;
